class EventEmitter<T extends Record<string, unknown[]>> {
  private listeners: { [K in keyof T]?: Array<(...args: T[K]) => void> } = {};

  off<K extends keyof T>(event: K, handler: (...args: T[K]) => void) {
    if (!this.listeners[event]) return;
    this.listeners[event] = this.listeners[event]?.filter(
      (fn) => fn !== handler,
    );
  }

  on<K extends keyof T>(event: K, callback: (...args: T[K]) => void) {
    this.listeners[event] = [...(this.listeners[event] || []), callback];
  }

  emit<K extends keyof T>(event: K, ...args: T[K]) {
    this.listeners[event]?.forEach((fn) => {
      fn(...args);
    });
  }
}

export default EventEmitter;

// 使用示例
// type AppEvents = {
//   login: [username: string];
//   logout: [];
// };

// const emitter = new EventEmitter<AppEvents>();
// emitter.on('login', (username) => console.log(`Welcome, ${username}!`));
// emitter.emit('login', 'Alice');
